# coding:utf-8
#########################
#   Author : Lion yu    #
#   Date : 2023/08/10   #
#   Id : SM2772         #
#########################
import os
from urllib.parse import quote
import json
import time
import hmac
import hashlib
import base64
import urllib.parse
import requests
from handle import Log, DingTalk_AccessToken, DingTalk_Secret, picPath, ProjectConfig
# from Notice import picPath


class DDnotices():
    def __init__(self):
        self.webhookURI = "https://oapi.dingtalk.com/robot/send"
        self.header = {
                        "Content-Type": "application/json",
                        "Charset": "UTF-8"
                        }
        self.secret = DingTalk_Secret
        self.timestamp = str((round(time.time() + 3500) * 1000))
        secret_enc = self.secret.encode('utf-8')
        string_to_sign = f"{self.timestamp}\n{self.secret}"
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        self.sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        self.webhook = f"{self.webhookURI}?access_token={DingTalk_AccessToken}&timestamp={self.timestamp}&sign={self.sign}"
        self.msgTemplate = {
            "msgtype" : "",
            "actionCard" : {
                "title" : "【数据统计通知】",
                "text" : "",
                "btnOrientation" : "0"
            }
        }
        
    def send_message(self, msg, btnsInfo:list, isAppoint:bool=False):
        msgExt = self.msgTemplate
        if isAppoint == True:
            msgExt['actionCard']['text'] = f"![screenshot]({picPath}) \n\n #### 【数据统计通知】 \n\n  {msg} \n\n项目缺陷看板数据刷新完毕  \nPS: 请使用公司网络 或 公司VPN访问"
        else:
            msgExt['actionCard']['text'] = f"![screenshot]({picPath}) \n\n #### 【数据统计通知】 \n\n 所有项目缺陷看板数据刷新完毕  \nPS: 请使用公司网络 或 公司VPN访问"
        msgExt['msgtype'] = "actionCard"
        btns = list()
        titles_name = list()
        for i in btnsInfo:
            actionURL = quote(i['actionURL'])
            link = f"dingtalk://dingtalkclient/page/link?url={actionURL}&pc_slide=false"
            titles_name.append(i['title'])
            btns.append({"title" : i['title'], "actionURL" : link})
        titles_name = ",".join(titles_name)
        msgExt['actionCard']['btns'] = btns
        message = msgExt
            
        message_json = json.dumps(message)
        info = requests.post(url=self.webhook,data=message_json,headers=self.header)
        if info.status_code == 200 and info.json()['errcode'] == 0:
            Log.info("钉钉消息发送成功")
            return True
        else:
            Log.error(f'钉钉消息发送失败\nRESON : {info.json()}')
            return False